package linwen.wang.schedule.springboot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
// @EnableScheduling
public class TestClusterSpringbootSchedule {

    private static final String SCHEDUAL_KEY = "schedual_key";
    @Autowired
    private RedisTemplate redisTemplate;

    @PostConstruct
    private void init(){
        redisTemplate.opsForValue().set("count",1);
    }

    @Scheduled(cron = "0/3 * * * * ?")
    public void testSchedul() {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(SCHEDUAL_KEY, "value");
        if(flag){
            try{
                Thread.sleep(1000);
                int count = (int)redisTemplate.opsForValue().get("count");
                count++;
                redisTemplate.opsForValue().set("count",count);
                log.info("cron schedul {}",count);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }finally {
                redisTemplate.delete(SCHEDUAL_KEY);
            }
        }
    }
}
